import os
import logging

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from MetroNorthDao import MetroNorthDao

""" Just display the main page """
class Index(webapp.RequestHandler):
    
    def __init__(self):
        metroNorthDao = MetroNorthDao()
        self.stationList = sorted(metroNorthDao.getStations().itervalues())
        logging.debug("Loaded station list")
        #elf.stationList = ("STAMFORD","DARIEN")
        
    def get(self):
                    
        template_values = {
            'stationList': self.stationList,
            }       

        path = os.path.join(os.path.dirname(__file__) + '/templates', 'metro_north.html')
        self.response.out.write(template.render(path, template_values))
        
""" Get the schedule for the requested stations. """
class GetSchedule(webapp.RequestHandler):
    def get(self):
        
        station1 = self.request.get('station1')
        station2 = self.request.get('station2')
        hour = self.request.get("hour")
        date = self.request.get("date")
        am_pm = self.request.get("am_pm")
        
        logging.debug("Have request for %s %s %s %s %s" % (station1, station2, hour, date, am_pm))
        
        metroNorthDao = MetroNorthDao()
        outTrains = metroNorthDao.getSchedulesByName(station1, station2, date, hour, am_pm)
        returnTrains = metroNorthDao.getSchedulesByName(station2, station1, date, hour, am_pm)       
         
        #outTrains = (["6:00","9:00"],["5:00","6:00"])
        #returnTrains = (["6:00","9:00"],["5:00","6:00"])
                    
        template_values = {
            'time': hour + " " + am_pm + " " + date,
            'outTrains': outTrains,
            'returnTrains': returnTrains,
            'station1': station1,
            'station2': station2,
            }
        
        path = os.path.join(os.path.dirname(__file__) + '/templates', 'schedules.html')
        self.response.out.write(template.render(path, template_values))       

application = webapp.WSGIApplication(
                                     [('/web/', Index),
                                      ('/web/schedule', GetSchedule)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()